
//
//  NSObject+Utilities.m
//  WCN
//
//  Created by 杨鑫 on 15/6/6.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "NSObject+Utilities.h"
#import <objc/runtime.h>

@implementation NSObject (Utilities)

+ (NSDictionary*)getObjectData:(id)obj
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    unsigned int propsCount;
    objc_property_t *props = class_copyPropertyList([obj class], &propsCount);
    for(int i = 0;i < propsCount; i++)
    {
        objc_property_t prop = props[i];
        
        NSString *propName = [NSString stringWithUTF8String:property_getName(prop)];
        id value = [obj valueForKey:propName];
        if(value == nil)
        {
//            value = [NSNull null];
            continue;
        }
        else
        {
            value = [self getObjectInternal:value];
            if (value == nil) {
                continue;
            }
        }
        [dic setObject:value forKey:propName];
    }
    return dic;
}

+ (id)getObjectInternal:(id)obj
{
    if([obj isKindOfClass:[NSString class]] || [obj isKindOfClass:[NSNumber class]] || [obj isKindOfClass:[NSNull class]])
    {
        return obj;
    }
    
    if([obj isKindOfClass:[NSArray class]])
    {
        NSArray *objarr = obj;
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:objarr.count];
        for(int i = 0;i < objarr.count; i++)
        {
            [arr setObject:[self getObjectInternal:[objarr objectAtIndex:i]] atIndexedSubscript:i];
        }
        return arr;
    }
    
    if([obj isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *objdic = obj;
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:[objdic count]];
        for(NSString *key in objdic.allKeys)
        {
            [dic setObject:[self getObjectInternal:[objdic objectForKey:key]] forKey:key];
        }
        return dic;
    }
    
    if ([obj isKindOfClass:[NSSet class]]) {
        return [NSNull null];
    }
    
    return [self getObjectData:obj];
}

- (void)performBlock:(void (^)(void))block afterDelay:(NSTimeInterval)delay
{
    //可能不需要家copy
    block = [block copy];
    [self performSelector:@selector(fireBlockAfterDelay:)
               withObject:block
               afterDelay:delay];
}

- (void)fireBlockAfterDelay:(void (^)(void))block
{
    block();
}

//keys
static char testKey;

- (id)test
{
    return objc_getAssociatedObject(self, &testKey);
}

- (void)setTest:(id)test
{
    objc_setAssociatedObject(self, &testKey, test, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end
